package com.pda.yuanjing.pages.sybom;

import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.apkfuns.logutils.LogUtils;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.pda.yuanjing.PDApp;
import com.pda.yuanjing.R;
import com.pda.yuanjing.beanin.JieDianBeanIn;
import com.pda.yuanjing.beanin.ScanfBeanIn;
import com.pda.yuanjing.beanout.CodeBomBeanOut;
import com.pda.yuanjing.beanout.JDBeanNewOut;
import com.pda.yuanjing.beanout.PPBeanOut;
import com.pda.yuanjing.beanout.SCBeanOut;
import com.pda.yuanjing.boardcast.CustomReceiver;
import com.pda.yuanjing.boardcast.ScannerInterface;
import com.pda.yuanjing.dialog.product.ProductAllDialog;
import com.pda.yuanjing.dialog.product.ProductDialog;
import com.pda.yuanjing.dialog.product.ProducttDialog;
import com.public_module.basemvp.activity.BaseActivity_noMVP;
import com.public_module.config.ApiYJ;
import com.public_module.config.SetConfig;
import com.public_module.tools.SharedPreferencesManger;
import com.public_module.tools.StringProcess;
import com.public_module.tools.VoiceUtils;

import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

public class BomBJActivity extends BaseActivity_noMVP {
    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.rltitle)
    RelativeLayout rltitle;
    @BindView(R.id.tvstore0)
    TextView tvstore0;
    @BindView(R.id.ll0)
    LinearLayout ll0;
    @BindView(R.id.tvstore)
    TextView tvstore;
    @BindView(R.id.ll1)
    LinearLayout ll1;
    @BindView(R.id.tvjxs)
    TextView tvjxs;
    @BindView(R.id.ll8)
    LinearLayout ll8;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.ll2)
    LinearLayout ll2;
    @BindView(R.id.edcode)
    EditText edcode;
    @BindView(R.id.ll3)
    LinearLayout ll3;
    @BindView(R.id.listView)
    ListView listView;

    private String TAG = "BomBJActivity";
    CodeBomBeanOut.DataDTO.ListDTO listDTO = null;
    ProductDialog productDialog1;
    ProductDialog productDialog2;
    int flagIndex = 0;
    private OptionsPickerView pickerView;
    ScannerInterface scanner;
    CustomReceiver customReceiver = null;
    VoiceUtils voiceUtils;
    Gson gson;
    OkHttpClient client;
    ApiYJ apisync;

    protected void initdata() {
        tvTitle.setText("BOM" + SharedPreferencesManger.getRealName());
        //listDTO = (CodeBomBeanOut.DataDTO.ListDTO) getIntent().getSerializableExtra(PDApp.process);
        listDTO = new CodeBomBeanOut.DataDTO.ListDTO();
        if (listDTO.getBomID() != null && !listDTO.getBomID().equals("")) {
            tvstore.setText(listDTO.getMaterialsName());
            tvjxs.setText(listDTO.getJieDianName());
            if (listDTO.getIsNeedScan().equals("1")) {
                checkbox.setChecked(true);
            } else {
                checkbox.setChecked(false);
            }
            edcode.setText(listDTO.getContainNums());
        }

        edcode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                listDTO.setContainNums(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        gson = new Gson();
        client = new OkHttpClient.Builder()
                .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                .followRedirects(false)
                .build();
        apisync = new Retrofit.Builder()
                .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                .client(client)
                .build().create(ApiYJ.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bombj);
        ButterKnife.bind(this);
        scanner = new ScannerInterface(this);
        scanner.setOutputMode(1);
        customReceiver = new CustomReceiver(
                new CustomReceiver.PListener1() {
                    @Override
                    public void setData(CustomReceiver.Dataa dataa) {
                    }
                },
                new CustomReceiver.PListener2() {
                    @Override
                    public void setText(String string) {
                        String ss = StringProcess.codeMat(string);
                        if (!PDApp.scanfp) {
                            getRes(flagIndex, ss);
                            return;
                        }
                    }
                });
        IntentFilter filter = new IntentFilter();
        filter.addAction(ScannerInterface.RES_ACTION);
        registerReceiver(customReceiver, filter);
        voiceUtils = new VoiceUtils(this);
        initdata();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (customReceiver != null) {
            unregisterReceiver(customReceiver);
        }
        if (scanner != null) {
            scanner.setOutputMode(0);
        }
    }

    public void add() {
        try {
            if (listDTO.getProductID() == null || listDTO.getProductID().equals("")) {
                showMsg("请选择组件");
                return;
            }
            if (listDTO.getMaterialsID() == null || listDTO.getMaterialsID().equals("")) {
                showMsg("请选择子件");
                return;
            }
            if (listDTO.getProcessID() == null || listDTO.getProcessID().equals("")) {
                showMsg("请选择节点");
                return;
            }
            if (listDTO.getContainNums() == null || listDTO.getContainNums().equals("")) {
                showMsg("请填写数量");
                return;
            }
            JieDianBeanIn jieDianBeanIn = new JieDianBeanIn();
            jieDianBeanIn.setAction("SY_BOMEdit");
            jieDianBeanIn.setCid(SharedPreferencesManger.getCid());
            jieDianBeanIn.setUserID(SharedPreferencesManger.getUid());
            jieDianBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            jieDianBeanIn.setBomID("-1");
            jieDianBeanIn.setProductID(listDTO.getProductID());
            jieDianBeanIn.setMaterialsID(listDTO.getMaterialsID());
            jieDianBeanIn.setContainNums(listDTO.getContainNums());
            jieDianBeanIn.setProcessID(Integer.parseInt(listDTO.getProcessID()));
            jieDianBeanIn.setJieDianName(listDTO.getJieDianName());
            jieDianBeanIn.setIsNeedScan(listDTO.getIsNeedScan());
            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(jieDianBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            JDBeanNewOut jdBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), JDBeanNewOut.class);
                            if (jdBeanOut.getErrcode() == 0) {
                                Looper.prepare();
                                showMsg("提交完成");
                                query(listDTO.getProductID());
                                Looper.loop();
                            } else {
                                Looper.prepare();
                                showMsg(jdBeanOut.getErrmsg());
                                Looper.loop();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return;
        }
    }

    public void edit() {
        try {
            if (listDTO.getContainNums() == null || listDTO.getContainNums().equals("")) {
                showMsg("请填写数量");
                return;
            }
            JieDianBeanIn jieDianBeanIn = new JieDianBeanIn();
            jieDianBeanIn.setAction("SY_BOMEdit");
            jieDianBeanIn.setCid(SharedPreferencesManger.getCid());
            jieDianBeanIn.setUserID(SharedPreferencesManger.getUid());
            jieDianBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            jieDianBeanIn.setBomID(listDTO.getBomID());
            jieDianBeanIn.setProductID(listDTO.getProductID());
            jieDianBeanIn.setMaterialsID(listDTO.getMaterialsID());
            jieDianBeanIn.setContainNums(listDTO.getContainNums());
            jieDianBeanIn.setProcessID(Integer.parseInt(listDTO.getProcessID()));
            jieDianBeanIn.setJieDianName(listDTO.getJieDianName());
            jieDianBeanIn.setIsNeedScan(listDTO.getIsNeedScan());
            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(jieDianBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            JDBeanNewOut jdBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), JDBeanNewOut.class);
                            if (jdBeanOut.getErrcode() == 0) {
                                Looper.prepare();
                                showMsg("提交完成");
                                finish();
                                Looper.loop();
                            } else {
                                Looper.prepare();
                                showMsg(jdBeanOut.getErrmsg());
                                Looper.loop();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return;
        }
    }

    public void query(String pid) {
        try {
            ScanfBeanIn scanfBeanIn = new ScanfBeanIn();
            scanfBeanIn.setAction("SY_BOMQuery");
            scanfBeanIn.setCid(SharedPreferencesManger.getCid());
            scanfBeanIn.setUserID(SharedPreferencesManger.getUid());
            scanfBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            scanfBeanIn.setCode("");
            scanfBeanIn.setProductID(pid);
            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(scanfBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            CodeBomBeanOut codeBomBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), CodeBomBeanOut.class);
                            if (codeBomBeanOut.getErrcode() == 0) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ItemAdapter itemAdapter = new ItemAdapter(BomBJActivity.this, codeBomBeanOut.getData().getList(),0);
                                        listView.setAdapter(itemAdapter);
                                    }
                                });
                            } else {
                                Looper.prepare();
                                showMsg(codeBomBeanOut.getErrmsg());
                                Looper.loop();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return;
        }
    }

    public void getRes(int ii, String code) {
        try {
            showProgress();
            Gson gson = new Gson();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                    .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                    .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                    .followRedirects(false)
                    .build();
            ApiYJ apisync = new Retrofit.Builder()
                    .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                    .client(client)
                    .build().create(ApiYJ.class);

            JieDianBeanIn jieDianBeanIn = new JieDianBeanIn();
            jieDianBeanIn.setAction("SY_QueryProdcutStoreByCode");
            jieDianBeanIn.setCid(SharedPreferencesManger.getCid());
            jieDianBeanIn.setUserID(SharedPreferencesManger.getUid());
            jieDianBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            jieDianBeanIn.setBaseType("1");
            jieDianBeanIn.setCodecc(code);

            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(jieDianBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            SCBeanOut scBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), SCBeanOut.class);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(ii==1){
                                        productDialog1.dismiss();
                                    }else if(ii==2){
                                        productDialog2.dismiss();
                                    }
                                        if (scBeanOut.getData().getIdStr().equals("-1")) {
                                            showMsg("未匹配到产品信息");
                                        } else {
                                            boolean flag = true;
                                            for (int i = 0; i <PDApp.productBeanOut.getData().size() ; i++) {
                                                if(PDApp.productBeanOut.getData().get(i).getId().equals(scBeanOut.getData().getIdStr())){
                                                    flag = false;
                                                    break;
                                                }
                                            }
                                            if(flag){
                                                showMsg("未匹配到产品信息");
                                                return;
                                            }
                                            if(ii==1){
                                                listDTO.setProductID(scBeanOut.getData().getIdStr());
                                                tvstore0.setText(scBeanOut.getData().getNameStr());
                                            }else if(ii==2){
                                                listDTO.setMaterialsID(scBeanOut.getData().getIdStr());
                                                tvstore.setText(scBeanOut.getData().getNameStr());
                                            }
                                            flagIndex = 0;
                                        }
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            hideProgress();
            return;
        }
    }

    @OnClick({R.id.iv_title_left, R.id.tvstore0, R.id.tvstore, R.id.tvjxs, R.id.checkbox, R.id.tv_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.tvstore0:
                tvstore0.setEnabled(false);
                flagIndex = 1;
                productDialog1 = new ProductDialog(mContext, R.style.CommentDialog, new ProductDialog.PriorityListener() {
                    @Override
                    public void setActivityText(String str, String str1, int num) {
                        listDTO.setProductID(str1);
                        tvstore0.setText(str);
                        flagIndex = 0;
                        productDialog1.dismiss();
                    }
                });
                WindowManager.LayoutParams lp0 = productDialog1.getWindow().getAttributes();
                lp0.gravity = Gravity.CENTER;
                productDialog1.show();
                tvstore0.setEnabled(true);
                break;
            case R.id.tvstore:
                tvstore.setEnabled(false);
                flagIndex = 2;
                productDialog2 = new ProductDialog(mContext, R.style.CommentDialog, new ProductDialog.PriorityListener() {
                    @Override
                    public void setActivityText(String str, String str1, int num) {
                        listDTO.setMaterialsID(str1);
                        tvstore.setText(str);
                        flagIndex = 0;
                        productDialog2.dismiss();
                    }
                });
                WindowManager.LayoutParams lp1 = productDialog2.getWindow().getAttributes();
                lp1.gravity = Gravity.CENTER;
                productDialog2.show();
                tvstore.setEnabled(true);
                break;
            case R.id.tvjxs:
                List<PPBeanOut.DataBean> options1Items = new ArrayList<>();
                List<List<String>> options2Items = new ArrayList<>();
                List<PPBeanOut.DataBean> listt = new ArrayList<>();
                PPBeanOut.DataBean temp = new PPBeanOut.DataBean();
                temp.setProcessID("-1");
                temp.setProcessName("全部流程");
                List<String> lists = new ArrayList<>();
                lists.add("全部工艺");
                temp.setListJieDianName(lists);
                listt.add(temp);
                listt.addAll(PDApp.ppBeanOut.getData());
                for (int i = 0; i < listt.size(); i++) {
                    PPBeanOut.DataBean pt = listt.get(i);
                    options1Items.add(pt);
                    List<String> ptl = new ArrayList<>();
                    for (int j = 0; j < listt.get(i).getListJieDianName().size(); j++) {
                        ptl.add(listt.get(i).getListJieDianName().get(j));
                    }
                    options2Items.add(ptl);
                }
                for (int i = 0; i < listt.size(); i++) {
                    PPBeanOut.DataBean pt = listt.get(i);
                    options1Items.add(pt);
                    List<String> ptl = new ArrayList<>();
                    for (int j = 0; j < listt.get(i).getListJieDianName().size(); j++) {
                        ptl.add(listt.get(i).getListJieDianName().get(j));
                    }
                    options2Items.add(ptl);
                }
                pickerView = new OptionsPickerBuilder(BomBJActivity.this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        String tx = options2Items.get(options1).get(options2);
                        listDTO.setProcessID(options1Items.get(options1).getProcessID());
                        listDTO.setJieDianName(tx);
                        tvjxs.setText(tx);
                    }
                })
                        .setTitleText("选择生产流程")
                        .setContentTextSize(20)//设置滚轮文字大小
                        .setTitleSize(20)
                        .setSubCalSize(20)
                        .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                        .setSelectOptions(0)//默认选中项
                        .setBgColor(Color.WHITE)
                        .setTitleBgColor(getResources().getColor(R.color.white))
                        .setTitleColor(getResources().getColor(R.color.black))
                        .setCancelColor(getResources().getColor(R.color.gray_high))
                        .setSubmitColor(getResources().getColor(R.color.blue))
                        .setTextColorCenter(getResources().getColor(R.color.black))
                        .setSubmitText("确定")
                        .setCancelText("取消")
                        .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                        .setOutSideColor(0x2A2A2A4F) //设置外部遮罩颜色
                        .build();
                pickerView.setPicker(options1Items, options2Items);
                pickerView.show();
                break;
            case R.id.checkbox:
                if (checkbox.isChecked()) {
                    listDTO.setIsNeedScan("1");
                } else {
                    listDTO.setIsNeedScan("0");
                }
                break;
            case R.id.tv_right:
                if (listDTO.getBomID().equals("")) {
                    add();
                } else {
                    edit();
                }
                break;
        }
    }
}
